/*
 * ImageLayerMerger.cpp
 *
 *  Created on: 2010-9-19
 *      Author: try
 */

#include "ImageLayerMerger.h"
#include "Layer.h"
#include "DrawPage.h"

namespace Ed {

  ImageLayerMerger::ImageLayerMerger(DrawPage* page):page(page) {

  }

  ImageLayerMerger::~ImageLayerMerger() {
    LayerBufferMap::iterator it = layerBufferMap.begin();
    for(; it != layerBufferMap.end(); it++){
      BufferItem* item = it->second;
      delete item->graphics;
      delete item->bitmap;
      delete item;
    }
  }

  /**
   * 返回BufferItem
   */
  ImageLayerMerger::BufferItem* ImageLayerMerger::getBufferItem(Layer* l){
    BufferItem* item = layerBufferMap[(long)l];
    if(!item){
      item = new BufferItem();
      layerBufferMap[(long)l] = item;
      item->bitmap = new Gdiplus::Bitmap((int)l->width(), (int)l->height());
      item->graphics =  new Gdiplus::Graphics(item->bitmap);

      item->graphics->SetPageUnit(Gdiplus::UnitPixel);
      item->graphics->SetSmoothingMode(Gdiplus::SmoothingModeHighQuality);
      item->graphics->SetTextRenderingHint(Gdiplus::TextRenderingHintClearTypeGridFit);
      item->graphics->Clear(l->getBackground());
    }
    return item;
  }


  bool ImageLayerMerger::merge(){
    Gdiplus::Graphics* pageGraphics = page->getPageGraphics();
    const std::vector<Layer*>* layers = (const std::vector<Layer*>*)page->getLayers();
    std::vector<Layer*>::const_iterator it = layers->begin();
    for(; it !=layers->end(); it++){
      Layer* layer = *it;
      BufferItem* item = getBufferItem(layer);
      layer->draw(item->graphics);
      pageGraphics->DrawImage(item->bitmap, layer->x(), layer->y());
    }
    return true;
  }


}
